//
//  YBStartRecordController.m
//  孕妙
//
//  Created by Raoy on 16/4/8.
//  Copyright © 2016年 是源科技. All rights reserved.
//

#import "YBStartRecordController.h"
#import "YBStartRecordTableViewCell.h"
#import "YBWeightInputController.h"
#import "YBTiWenInputController.h"
#import "YBXueYaInputController.h"
#import "YBXueTangInputController.h"
#import "YBHeartInputController.h"
#import "YBTaiHeartInputViewController.h"
#import "passValue.h"
#import "AFNetworking.h"
#import "YBHealthParmater.h"
#import "MJExtension.h"

//二维码
#import "ScanerQRcodeVC.h"

#define cellHeight (60 * (DeviceHeight / 480))

//设备类型
typedef NS_ENUM(NSUInteger, ProductScale){
    weight,
    tiWen,
    xueTang,
    xueYa,
    xingLv,
    taiXing
};

@interface YBStartRecordController ()<UITableViewDelegate, UITableViewDataSource, UIAlertViewDelegate>

@property(strong, nonatomic)UITableView *RecordListTableView;
@property(strong, nonatomic)NSArray *itemImageArray;
@property(copy, nonatomic)NSArray *theDayValue;

//存放设备激活类型字典
@property (nonatomic, copy)NSMutableDictionary *productDictM;
@property (nonatomic, assign)ProductScale pScale;

@end

@implementation YBStartRecordController



- (void)setTheDayValue:(NSArray *)theDayValue
{
    _theDayValue = theDayValue;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"开始记录";
    self.view.backgroundColor = [UIColor clearColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationController.navigationBar.translucent = YES;

    //UITableView
    _RecordListTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, SYNavigateHeight, DeviceWidth, DeviceHeight ) style:UITableViewStylePlain];
    _RecordListTableView.bounces = NO;
    _RecordListTableView.delegate = self;
    _RecordListTableView.dataSource = self;
    _RecordListTableView.backgroundColor = SYColor(245, 245, 245);
    [self.view addSubview:self.RecordListTableView];
    
    UIView *hongseLabel = [[UIView alloc] initWithFrame:CGRectMake(0, DeviceHeight - 10, DeviceWidth, 10)];
    hongseLabel.backgroundColor = SYColor(253, 207, 230);
    [self.view addSubview:hongseLabel];
    
    //获取设备激活类型数据
    [self getUserHealthProductType];
}

- (NSMutableDictionary *)productDictM
{
    if (_productDictM == nil) {
        _productDictM = [NSMutableDictionary dictionary];
    }
    
    return _productDictM;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.itemLArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
   
    return cellHeight;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellid = @"StartRecordCellID";
    YBStartRecordTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellid];
    
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"YBStartRecordTableViewCell" owner:self options:nil] lastObject];
        if ([[self.itemLArray objectAtIndex:indexPath.row] isEqualToString:@"体重"]) {
            cell.itemL.text = @"体成分";
        }else{
        
            cell.itemL.text = [self.itemLArray objectAtIndex:indexPath.row];
        }
        
        cell.backgroundColor = SYColor(245, 245, 245);
    }
    YBHealthParmater *tempParmater = self.theDayValue.firstObject;
    if ([[self.itemLArray objectAtIndex:indexPath.row] isEqualToString:@"体重"]) {
        if (tempParmater.weight) {
            cell.itemValueL.text = [NSString stringWithFormat:@"%0.1f kg", tempParmater.weight];
            cell.recoredFlagL.text = @"已检测";
            [cell.recoredFlagL setTextColor:SYColor(69, 188, 37)];
        }
        cell.imageViewOne.image = [UIImage imageNamed:@"record_weight"];
        [cell.inputBtn addTarget:self action:@selector(weightBtnSEL:) forControlEvents:UIControlEventTouchUpInside];
        
    }else if ([[self.itemLArray objectAtIndex:indexPath.row] isEqualToString:@"体温"]){
        if (tempParmater.tem) {
            cell.itemValueL.text = [NSString stringWithFormat:@"%0.1f °C", tempParmater.tem];
            cell.recoredFlagL.text = @"已检测";
            [cell.recoredFlagL setTextColor:SYColor(69, 188, 37)];
        }
        cell.imageViewOne.image = [UIImage imageNamed:@"record_temperature"];
        [cell.inputBtn addTarget:self action:@selector(tiWenBtnSEL:) forControlEvents:UIControlEventTouchUpInside];
        
        
    }else if([[self.itemLArray objectAtIndex:indexPath.row] isEqualToString:@"血压"]){
        if (tempParmater.dbp) {
            cell.itemValueL.text = [NSString stringWithFormat:@"高：%ld 低：%ld", (long)tempParmater.dbp, (long)tempParmater.sbp];
            cell.recoredFlagL.text = @"已检测";
            [cell.recoredFlagL setTextColor:SYColor(69, 188, 37)];
        }
        cell.imageViewOne.image = [UIImage imageNamed:@"record_mmHg"];
        [cell.inputBtn addTarget:self action:@selector(xueYaBtnSEL:) forControlEvents:UIControlEventTouchUpInside];
       
    }else if ([[self.itemLArray objectAtIndex:indexPath.row] isEqualToString:@"血糖"]){
        if (tempParmater.bloodG) {
            cell.itemValueL.text = [NSString stringWithFormat:@"%0.1f mmol/L", tempParmater.bloodG];
            cell.recoredFlagL.text = @"已检测";
            [cell.recoredFlagL setTextColor:SYColor(69, 188, 37)];
        }
        cell.imageViewOne.image = [UIImage imageNamed:@"record_bloodsugar"];
        [cell.inputBtn addTarget:self action:@selector(xueTangBtnSEL:) forControlEvents:UIControlEventTouchUpInside];
       
    }else if ([[self.itemLArray objectAtIndex:indexPath.row] isEqualToString:@"心率"]){
        if (tempParmater.heartRate) {
            cell.itemValueL.text = [NSString stringWithFormat:@"%ld 次/min", (long)tempParmater.heartRate];
            cell.recoredFlagL.text = @"已检测";
            [cell.recoredFlagL setTextColor:SYColor(69, 188, 37)];
        }
        cell.imageViewOne.image = [UIImage imageNamed:@"record_bpm"];
        [cell.inputBtn addTarget:self action:@selector(heartRateBtnSEL:) forControlEvents:UIControlEventTouchUpInside];
        
    }else if ([[self.itemLArray objectAtIndex:indexPath.row] isEqualToString:@"胎心"]){
        
        cell.imageViewOne.image = [UIImage imageNamed:@"record_FHR"];
        [cell.inputBtn addTarget:self action:@selector(TaiHeartRateBtnSEL:) forControlEvents:UIControlEventTouchUpInside];
        
    }
    
    
    
    return cell;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    
    [self getUserParmaterData:[passValue passValue].passValueName username:[passValue passValue].saveDataUserName];
}

- (void)viewDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
    
}

/**
 * 请求当天的监测数据
 */
- (void)getUserParmaterData:(NSString *)account username:(NSString *)username
{
 
    // 1.创建请求管理对象
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    // 2.封装请求参数
    NSDateComponents *tempComp  = [self convertFromDateToDateComp:[NSDate date]];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"account"] = account;
    params[@"username"] = username;
    params[@"devicename"] = @"phealth";
    params[@"date"] = [NSString stringWithFormat:@"%ld%02ld%02ld000000", (long)tempComp.year, (long)tempComp.month, (long)tempComp.day];
   
    // 3.发送请求
    [mgr GET:URL_Health_baby_getDevUseInfo parameters:params
     success:^(AFHTTPRequestOperation *operation, id responseObject) {
         NSLog(@"wwwwwresponseObject:%@", responseObject);
         if (responseObject[@"response"]) {
             // 取出data字典数组
             NSArray *dataDictArraye = responseObject[@"data"];
             self.theDayValue = [YBHealthParmater mj_objectArrayWithKeyValuesArray:dataDictArraye];
             [self.RecordListTableView reloadData];
               YMLog(@"data = %@",self.theDayValue);
             
             // 请求成功
             //                 NSLog(@"请求321的数据：%@", responseObject);
         } else {
             [MBProgressHUD showError:@"请求网络失败，请检查网络连接"];
         }
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         [MBProgressHUD showError:@"请求网络失败，请检查网络连接"];
     }];
}

/**
 * 获得手机时间(年月日时分秒)
 */
- (NSDateComponents *)convertFromDateToDateComp:(NSDate *)tempDate
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    int unit = NSCalendarUnitDay | NSCalendarUnitMonth |  NSCalendarUnitYear | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond | NSCalendarUnitWeekday;
    
    // 1.获得当前时间的年月日
    NSDateComponents *nowCmps = [calendar components:unit fromDate:tempDate];
    
    return nowCmps;
}



- (void)weightBtnSEL:(id)sender
{
    _pScale = weight;
    if (_productDictM == nil) {
        [MBProgressHUD showError:@"用户未注册此功能，请重新注册账号"];
        return;
    }
    [self getUserHealthProductSalesSearch:[self.productDictM objectForKey:@"体重秤"]];
}

- (void)tiWenBtnSEL:(id)sender
{
    YBTiWenInputController *tiwenVC = [[YBTiWenInputController alloc] init];
    [self.navigationController pushViewController:tiwenVC animated:YES];
}

- (void)xueYaBtnSEL:(id)sender
{
    YBXueYaInputController *xueyaVC = [[YBXueYaInputController alloc] init];
    [self.navigationController pushViewController:xueyaVC animated:YES];
}

- (void)xueTangBtnSEL:(id)sender
{
    
   YBXueTangInputController *xuetangVC = [[YBXueTangInputController alloc] init];

    [self.navigationController pushViewController:xuetangVC animated:YES];
}

- (void)heartRateBtnSEL:(id)sender
{
    YBHeartInputController *heartVC = [[YBHeartInputController alloc] init];
    [self.navigationController pushViewController:heartVC animated:YES];
}

- (void)TaiHeartRateBtnSEL:(id)sender
{
    YBTaiHeartInputViewController *taiHeartVC = [[YBTaiHeartInputViewController alloc] init];
    [self.navigationController pushViewController:taiHeartVC animated:YES];
}

- (void)dealloc
{
    self.theDayValue = nil;
}

#pragma mark -判断是否激活
//获取设备激活码类型
- (void)getUserHealthProductType
{
    //创建请求管理对象
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    
    [mgr GET:URL_Health_Hardware_Sys_ProductType parameters:nil success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        if ([responseObject objectForKey:@"response"]) {
            NSArray *tempArray = [responseObject objectForKey:@"data"];
            for (NSDictionary *tempDict in tempArray) {
                NSString *productName = [tempDict objectForKey:@"productTypeName"];
                NSString *productID = [tempDict objectForKey:@"id"];
                [self.productDictM setObject:productID forKey:productName];
            }
            NSLog(@"dict =  %@", self.productDictM);
        }else{
            [MBProgressHUD showError:[responseObject objectForKey:@"msg"]];
        }
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        [MBProgressHUD showError:@"请求网络失败，请检查网络连接"];
    }];
    
}

//验证是否开启了此模块
- (void)getUserHealthProductSalesSearch:(NSString *)str
{
    //创建请求管理对象
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    //设置请求参数
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setObject:[passValue passValue].userID forKey:@"uid"];
    [param setObject:str forKey:@"productTypeId"];
    
    [mgr GET:URL_Health_Hardware_Sys_ProductSales parameters:param success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        NSLog(@"responseObject = %@", responseObject);
        if ([responseObject objectForKey:@"response"]) {
            //code == 0表示激活了
            if ([[responseObject objectForKey:@"code"] integerValue]) {
                [self judgePushIfActivateVC:NO];
            }else{
                [self judgePushIfActivateVC:YES];
            }
            
        }else{
            [MBProgressHUD showError:[responseObject objectForKey:@"msg"]];
        }
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        [MBProgressHUD showError:@"请求网络失败，请检查网络连接"];
    }];
    
}

//是否进入激活页面
- (void)judgePushIfActivateVC:(BOOL)flag
{
    switch (_pScale) {
        case weight:
            if (flag) {
                YBWeightInputController *weightVC = [[YBWeightInputController alloc] init];
                [self.navigationController pushViewController:weightVC animated:YES];
            }else {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil
                                                                message:@"确定是否激活此功能？"
                                                               delegate:self
                                                      cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
                [alert show];
            }
            break;
        case tiWen:
            break;
        case xueTang:
            break;
        case xueYa:
            break;
        case xingLv:
            break;
        case taiXing:
            break;
            
        default:
            break;
    }
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        ScanerQRcodeVC *sQRcodeVC = [[ScanerQRcodeVC alloc] init];
        [self.navigationController pushViewController:sQRcodeVC animated:YES];
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
